

//2.当使用js生成多个窗口时，对象冲突的问题: 可通过 id的方式访问 fin
//3.数据的存储，生成一个不可见div,保存数据在div的data属性中。 完成
//4.对加载数据tree的格式要求:
//    1.tree中attributes属性 必须有id,并且和 tree 中的id 一致,这样才能实现 左选功能
//    2.tree中attributes属性 必须有isLeaf属性,已保证右旋的时候,分支节点不被选入

//构造函数
//str_idPrefix：id 前缀,obj_treeParameter:
//str_contentDivId: 外层div 的id
//obj_treeParameter: 构造tree的参数:其中 tree的格式有特殊要求:
//obj_dataGridParameter:构造 datagrid的参数
//fun_okCall:回调函数,格式 functionName(array_result):其中array_result 为选中的最终数据
//array_customFun:自定义参数:格式为[{label:"新增",function:funA}]
function ltrdSelectSingle(str_contentDivId,str_idPrefix,str_dlgTitle,obj_treeParameter,obj_dataGridParameter,fun_okCall,str_checkedId,array_customFun){
	var self=new Object();
	
	/*var self.ez_tree;
	var self.ez_datagrid;
	var selt.bool_isOk=false;
	var self.fun_getLtrdData;//最终选择结果
	var self.fun_destroyPanel;*/

	self.ez_panel=ltrdSelectSingle_createPanelAndLayout(str_idPrefix,str_contentDivId,array_customFun);
	self.ez_tree=ltrdSelectSingle_creatEzTree(str_idPrefix,obj_treeParameter,obj_dataGridParameter,str_checkedId);
	//self.ez_datagrid=ltrdSelectSingle_createEzDatagrid(str_idPrefix,obj_dataGridParameter);
	

	//ltrdSelectSingle_initLtrdData(str_idPrefix);
	ltrdSelectSingle_registerInnerFunctionButtons(str_idPrefix,fun_okCall);
	
	ltrdSelectSingle_registerCustomFunction(str_idPrefix,array_customFun);
	
	self.fun_getLtrdData=function getSelfLtrdData(){
		return ltrdSelectSingle_getLtrdData(str_idPrefix);
	};

	self.fun_destroyPanel=function destroySelfPanel(){
		self.ez_panel.panel("destroy");
	};

	return self;
}


//生成Panel,layout div和eayui对象
//str_idPrefix：id 前缀,obj_treeParameter:
//str_contentDivId: 外层div 的id
function ltrdSelectSingle_createPanelAndLayout(str_idPrefix,str_contentDivId,str_dlgTitle){
	var str_panel=["<div  class=\"easyui-panel\"  style=\"width:700px;height:400px;\" ></div>"].join("");
	var div_panel=$(str_panel).attr("id",str_idPrefix+"-ltrdSelectSingle-panel");

	var str_layout=["<div  class=\"easyui-layout\" data-options=\"fit:true\" ></div>"].join("");
	var div_layout=$(str_layout).attr("id",str_idPrefix+"-ltrdSelectSingle-layout");
	
	var str_westRegion=["<div data-options=\"region:\'west\',iconCls:\'icon-reload\',title:\'选择树\' , collapsible:false ,border:false\" style=\"width:340px;\">",
						"<div  style=\"vertical-align: middle;border-bottom: 1px solid #E3E3E3;margin-bottom: 10px;\">",
						"<label for=\"exampleInputName2\" style=\"margin-left: 10px;\">关键词</label>",
						"<input id=\""+str_idPrefix+"-ltrdsSelect-keyword\" type=\"text\" style=\"width: 70px;margin: 0 5px 0 5px;\" placeholder=\"\" >",
						"<button type=\"button\" class=\"\" id=\""+str_idPrefix+"-ltrdSelectSingle-filter\">筛选</button>",
						"<button type=\"button\" class=\"\" id=\""+str_idPrefix+"-ltrdSelectSingle-reset\">清除</button>",
						"</div>",
						"<div  class=\"easyui-panel\" data-options=\"border:false,noheader:true,fit:true\">",
						"<ul id=\""+str_idPrefix+"-ltrdSelectSingle-tree\"></ul>",
						"</div>",
						"</div>   "].join("");					
	var div_westRegion=$(str_westRegion);
	
	
	var str_centerRegion=["<div data-options=\"region:\'center\'\" style=\"background:#eee;width:10px ;\">",
						"</div>"].join("");
						

	var div_centerRegion=$(str_centerRegion);

	var str_eastRegion=["<div data-options=\"region:\'east\',iconCls:\'icon-reload\',title:\'已选择\' , collapsible:false,border:false\" style=\"width:340px;\">",
						"  <div id=\""+str_idPrefix+"-ltrdSelectSingle-datagrid\" class=\"easyui-panel\" data-options=\"border:false,noheader:true,fit:true,\">",
						"    <table id=\""+str_idPrefix+"-ltrdSelectSingle-dg\"></table>",
						"  </div>",
						"</div>"].join("");
	var div_eastRegion=$(str_eastRegion);
	
	var str_southRegion=["<div data-options=\"region:\'south\',iconCls:\'icon-reload\' , collapsible:false,doSize:true\" style=\"height:40px;\">",
						"  <div style=\"text-align: center;margin-top: 5px;\">",
						"    <button id=\""+str_idPrefix+"-ltrdSelectSingle-cancle\">取消</button>",
						"    <button id=\""+str_idPrefix+"-ltrdSelectSingle-ok\" style=\"margin-left: 20px;\">确认</button></div>",
						"	<div id=\""+str_idPrefix+"-ltrdSelectSingle-data\" data-ltrdData=\"[]\">",
						"</div>"].join("");
	var div_southRegion=$(str_southRegion);
	
	//div 合并
	$("#"+str_contentDivId).append(div_panel);
	div_panel.append(div_layout);
	div_layout.append(div_westRegion,div_centerRegion,div_eastRegion,div_southRegion);
	
	//生成 pannel、layout 对象
	var ez_panel=div_panel.dialog({    
	    title: str_dlgTitle,    
	    width:710,    
	    height: 550,    
	    closed: false,    
	    cache: false,    
	    modal: true,
	    nohead:true,
	    closable:false
	   	//queryParams:lrDlgQueryParams,
	   	//method:'post'
	}); 
	div_layout.layout();
	
	/*$("#"+str_idPrefix+"-ltrdSelectSingle-btn"+1).on("click",function(){
		array_customFun[0].func();
	});*/
	
	return ez_panel;
}

//str_idPrefix：id 前缀,obj_treeParameter: 构建tree 的参数
//目前属性 obj_treeParameter：url;queryParams
function ltrdSelectSingle_creatEzTree(str_idPrefix,obj_treeParameter,obj_dataGridParameter,str_checkedId){
		var str_ezTreeId=str_idPrefix+"-ltrdSelectSingle-tree";
		var ez_tree=$("#"+str_ezTreeId).tree({
			url:obj_treeParameter.url,
			method: 'get',
		    parentField : 'pid',
		    cascadeCheck:false,
			checkbox : false,
			onlyLeafCheck:true,
			queryParams : obj_treeParameter.queryParams,
			onBeforeLoad:function(){
				console.log("in onBeforeLoad");
				$.messager.progress({
					title : '提示',
					text : '正在加载数据~'
				});
			},
			onLoadSuccess:function(node,data){
				console.log("in onLoadSuccess");
				console.log(data);
				console.log(JSON.stringify(data));
				//$(this).tree('collapseAll');
				ltrdSelectSingle_initLtrdData(str_idPrefix,str_checkedId);
				ltrdSelectSingle_createEzDatagrid(str_idPrefix,obj_dataGridParameter);
				
				$.messager.progress('close');
				
			},
			onLoadError : function(node,data) { 
				console.log("in onLoadError");
		    	console.log(data);
		    	$.messager.progress('close');
		    	alert("数据加载失败，请于管理员联系:18639551912。");
		    },
		    onClick: function(node){
		    	var str_ezDatagridId=str_idPrefix+"-ltrdSelectSingle-datagrid";
				var jq_datagrid=$("#"+str_ezDatagridId);
				var ltrdData=new Array();
				
		    	
		 		console.log("hit targe="+node.text);  // 在用户点击的时候提示
		 		
		 		console.log(node);
		 		if(node.attributes && node.attributes.isLeaf){
		 			console.log(node.attributes);
		 			ltrdData.push(node.attributes);
		 			jq_datagrid.datagrid('loadData',ltrdData);
		 			ltrdSelectSingle_setLtrdData(str_idPrefix,ltrdData);
		 		}
		 		
		 	},
		 	onCheck: function(node){
				console.log("check"+node.text);  // 在用户点击的时候提示
			}
		});
		return ez_tree;
}

//构建dataGridEz对象
//str_idPrefix：id 前缀,obj_dataGridParameter: 构建datagrid 的参数
//目前属性 obj_treeParameter：url;queryParams
function ltrdSelectSingle_createEzDatagrid(str_idPrefix,obj_dataGridParameter){
	var arr_ltrdData=ltrdSelectSingle_getLtrdData(str_idPrefix);
	console.log("in createEzDatagrid");
	console.log(arr_ltrdData);
	var gridData=new Object();
	gridData.rows=arr_ltrdData;
	gridData.total=1;
	var str_ezDatagridId=str_idPrefix+"-ltrdSelectSingle-datagrid";
	var ez_datagrid=$("#"+str_ezDatagridId).datagrid({
		pagination:false,
		fit:true,
	  /*	fitColumns:true,*/
	    columns:obj_dataGridParameter.columns,
	    data:gridData,
	    onClickRow:function(index, row){
	    	 ez_datagrid.datagrid('deleteRow',index);
	    	 
	    	 var ltrdData=new Array();
	    	 ltrdSelectSingle_setLtrdData(str_idPrefix,ltrdData);
	    }
	   
	});
	return ez_datagrid;
}

//初始化 str_idPrefix-ltrdSelectSingle-data 数组数据
function ltrdSelectSingle_initLtrdData(str_idPrefix,str_checkedId){
	console.log("in init data");
	var str_ezTreeId=str_idPrefix+"-ltrdSelectSingle-tree";
	var jq_tree=$("#"+str_ezTreeId);
	var arr_ltrdData=new Array();
	//由于使用的是未使用checkbox ,check属性不能使用
	//var checkedId=jq_tree.tree('getChecked');
	//console.log(checkedId);
	// 查找一个节点并选择它
	console.log('str_checkedId='+str_checkedId);
	if(str_checkedId){
		var node = jq_tree.tree('find', str_checkedId);
		console.log(node);
		jq_tree.tree('select', node.target);
		jq_tree.tree('expandTo',node.target);
		arr_ltrdData.push(node.attributes);
	}
	var str_dataId=str_idPrefix+"-ltrdSelectSingle-data";
	var jq_divData=$("#"+str_dataId);
	jq_divData.data("lrtdData",arr_ltrdData);

}

//根据 str_idPrefix-ltrdSelectSingle-data 获得数组数据
//str_idPrefix: id 前缀,
function ltrdSelectSingle_getLtrdData(str_idPrefix){
	var str_dataId=str_idPrefix+"-ltrdSelectSingle-data";
	var jq_divData=$("#"+str_dataId);
	console.log(jq_divData);
	console.log(jq_divData.attr("data-ltrdData"));
	console.log(jq_divData.data("lrtdData"));
	return jq_divData.data("lrtdData");
}

//根据 str_idPrefix-ltrdSelectSingle-data 设置数组数据
//str_idPrefix: id 前缀,
//data: 数组数据
function ltrdSelectSingle_setLtrdData(str_idPrefix,data){
	var str_dataId=str_idPrefix+"-ltrdSelectSingle-data";
	var jq_divData=$("#"+str_dataId);
	jq_divData.data("lrtdData",data);
}

//注册ltrdSelectSingle 按钮 内部功能事件
function ltrdSelectSingle_registerInnerFunctionButtons(str_idPrefix,fun_okCall){
	//注册 文本框回车事件，回车直接筛选
	$('#'+str_idPrefix+'-ltrdsSelect-keyword').on('keydown',function(e){
		if(e.keyCode==13){
		  $("#"+str_idPrefix+"-ltrdSelectSingle-filter").click();
		}
	});
		
	//注册筛选按钮事件
	$("#"+str_idPrefix+"-ltrdSelectSingle-filter").on("click",function(){
		var str_ezTreeId=str_idPrefix+"-ltrdSelectSingle-tree";
		var jq_tree=$("#"+str_ezTreeId);
		var rootNodes=jq_tree.tree('getRoots');
		var j_ltrdSelectSingleName=$("#"+str_idPrefix+"-ltrdsSelect-keyword");
		var keyword=j_ltrdSelectSingleName.val();
		if(keyword.trim()!=''){
			$.each(rootNodes, function() {
				jq_tree.tree('expandAll',this.target);
			});
			jq_tree.tree('doFilter', keyword);
		}
	});
	
	
	//清除筛选按钮事件
	$("#"+str_idPrefix+"-ltrdSelectSingle-reset").on("click",function(){
		var str_ezTreeId=str_idPrefix+"-ltrdSelectSingle-tree";
		var jq_tree=$("#"+str_ezTreeId);
		
		j_ltrdSelectSingleName=$("#"+str_idPrefix+"-ltrdsSelect-keyword");
		j_ltrdSelectSingleName.val("");
		jq_tree.tree('doFilter', '');
		var arr_ltrdData=ltrdSelectSingle_getLtrdData(str_idPrefix);
		jq_tree.tree('collapseAll');
		console.log(arr_ltrdData);
		if(arr_ltrdData.length==1){
			var treeId=arr_ltrdData[0].id;
			console.log(treeId);
			var node = jq_tree.tree('find', treeId);
			jq_tree.tree('expandTo',node.target);
		}

	});
	
	//注册 右选事件
	/*$("#"+str_idPrefix+"-ltrdSelectSingle-right").on("click",function(){
		var str_ezTreeId=str_idPrefix+"-ltrdSelectSingle-tree";
		var jq_tree=$("#"+str_ezTreeId);
		var str_ezDatagridId=str_idPrefix+"-ltrdSelectSingle-datagrid";
		var jq_datagrid=$("#"+str_ezDatagridId);
		var ltrdData=ltrdSelectSingle_getLtrdData(str_idPrefix);
		
		var nodes = jq_tree.tree('getChecked');
		ltrdData.length=0;
		$.each(nodes, function() {
			if(this.attributes.isLeaf)
				ltrdData.push(this.attributes);
		});
		console.log(ltrdData);
		jq_datagrid.datagrid('loadData',ltrdData);
		ltrdSelectSingle_setLtrdData(str_idPrefix,ltrdData);
	});*/
	
	////注册 左选事件
	/*$("#"+str_idPrefix+"-ltrdSelectSingle-left").on("click",function(){
		var str_ezTreeId=str_idPrefix+"-ltrdSelectSingle-tree";
		var jq_tree=$("#"+str_ezTreeId);
		var str_ezDatagridId=str_idPrefix+"-ltrdSelectSingle-datagrid";
		var jq_datagrid=$("#"+str_ezDatagridId);
		
		var selectionRows=jq_datagrid.datagrid('getSelections');
		
		console.log(selectionRows);
		$.each(selectionRows, function() {
			console.log(this.id);
			var node = jq_tree.tree('find', this.id);
			console.log(node);
			if(node){
				jq_tree.tree('uncheck', node.target);
				console.log(this.id+"unchecked.");
			}
			var rowIndex=jq_datagrid.datagrid('getRowIndex',this);
			jq_datagrid.datagrid('deleteRow',rowIndex);
		});
		
		var array_ltrdData=new Array();
		var nodes = jq_tree.tree('getChecked');
		$.each(nodes, function() {
			if(!this.attributes.ignored)
				array_ltrdData.push(this.attributes);
		});
		
		ltrdSelectSingle_setLtrdData(str_idPrefix,array_ltrdData);
		
	});*/
	
	//注册 全右选事件
	/*$("#"+str_idPrefix+"-ltrdSelectSingle-right_all").on("click",function(){
		var str_ezTreeId=str_idPrefix+"-ltrdSelectSingle-tree";
		var jq_tree=$("#"+str_ezTreeId);
		var str_ezDatagridId=str_idPrefix+"-ltrdSelectSingle-datagrid";
		var jq_datagrid=$("#"+str_ezDatagridId);
		
		var flag=new Object();
		flag.checked=true;
		treeChecked(flag,str_idPrefix+"-ltrdSelectSingle-tree");
		var nodes = jq_tree.tree('getChecked');
		var ltrdData=ltrdSelectSingle_getLtrdData(str_idPrefix);
		ltrdData.length=0;
		$.each(nodes, function() {
			if(this.attributes.isLeaf)
				ltrdData.push(this.attributes);
		});
		
		jq_datagrid.datagrid('loadData',ltrdData);
		ltrdSelectSingle_setLtrdData(str_idPrefix,ltrdData);
		console.log(ltrdData);
	});*/
	
	
	//注册 全左选事件
	/*$("#"+str_idPrefix+"-ltrdSelectSingle-left_all").on("click",function(){
		var str_ezDatagridId=str_idPrefix+"-ltrdSelectSingle-datagrid";
		var jq_datagrid=$("#"+str_ezDatagridId);
		var ltrdData=ltrdSelectSingle_getLtrdData(str_idPrefix);
		
		var flag=new Object();
		flag.checked=false;
		treeChecked(flag,str_idPrefix+"-ltrdSelectSingle-tree");
		ltrdData.length=0;
		jq_datagrid.datagrid('loadData',ltrdData);
		ltrdSelectSingle_setLtrdData(str_idPrefix,ltrdData);
		console.log(ltrdData);
	});*/

	//注册取消事件
	$("#"+str_idPrefix+"-ltrdSelectSingle-cancle").on("click",function(){
		var str_panelId=str_idPrefix+"-ltrdSelectSingle-panel";
		var jq_pannel=$("#"+str_panelId);
		jq_pannel.dialog('destroy');
		
	});
	
	//注册确认ok事件
	$("#"+str_idPrefix+"-ltrdSelectSingle-ok").on("click",function(){
		var array_ltrdData=ltrdSelectSingle_getLtrdData(str_idPrefix);
		fun_okCall(array_ltrdData);
		var str_panelId=str_idPrefix+"-ltrdSelectSingle-panel";
		var jq_pannel=$("#"+str_panelId);
		jq_pannel.panel('destroy');
	});
}	

function ltrdSelectSingle_registerCustomFunction(str_idPrefix,array_customFun){
	var str_cancleId=str_idPrefix+"-ltrdSelectSingle-cancle";
	var jq_cancleBtn=$("#"+str_cancleId);
	//根据array_customFun增加新的按钮
	if(typeof(array_customFun) !=  "undefined" && array_customFun.length > 0 ){
    	console.log(array_customFun);
    	var index=1;
    	$.each(array_customFun, function() {
    		var self=this;
    		var str_customBtn=["<button style=\"margin-left: 20px;\" id=\""+str_idPrefix+"-ltrdSelectSingle-btn"+index+"\">"+this.label+"</button>"].join("");
			var jq_customBtn=$(str_customBtn);
			//self.func();
			console.log(self);
			jq_cancleBtn.after(str_customBtn);
			$("#"+str_idPrefix+"-ltrdSelectSingle-btn"+index).on("click",function(){
				self.func();
			});
			index=index+1;
    	});
	} 	
}
